package com.victor.modular.system.controller;

import com.victor.common.annotion.Permission;
import com.victor.common.annotion.log.BussinessLog;
import com.victor.common.constant.Dict;
import com.victor.common.constant.factory.ConstantFactory;
import com.victor.common.constant.tips.Tip;
import com.victor.common.controller.BaseController;
import com.victor.common.exception.BizExceptionEnum;
import com.victor.common.exception.BussinessException;
//import com.victor.common.export.dictmap.CustomExport;
import com.victor.common.persistence.dao.CustomMapper;
import com.victor.common.persistence.model.Custom;
import com.victor.core.log.LogObjectHolder;
import com.victor.core.support.BeanKit;
import com.victor.core.util.ExcelReport;
import com.victor.core.util.ToolUtil;
//import com.victor.modular.system.dao.CustomCodeDao;
import com.victor.modular.system.dao.CustomDao;
import com.victor.modular.system.service.ICustomService;
import com.victor.modular.system.transfer.CustomDto;
import com.victor.modular.system.transfer.FileDto;
import com.victor.modular.system.warpper.CustomWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RequestMapping("/custom")
@Controller
public class CustomController extends BaseController {
    private static String PREFIX = "/system/custom/";
    @Autowired
    private CustomDao customDao;
    @Autowired
    private ICustomService customService;
    @Autowired
    private CustomMapper customMapper;
//    @Autowired
//    CustomCodeDao customCodeDao;
    /**
     * 跳转到 观众列表页面
     */
    @RequestMapping("")
    public String index(Model model) {
//        model.addAttribute("businessTypeList", ConstantFactory.me().getBusinessList());
//        model.addAttribute("industryTypeList", ConstantFactory.me().getIndustryList());
//        model.addAttribute("propertyList", ConstantFactory.me().getPropertyList());
        return PREFIX + "custom.html";
    }



    /**
     * 查询观众列表
     */
    @RequestMapping("/list")
    @ResponseBody
    @Permission
    public Object list(CustomDto params) {
        List<Map<String, Object>> list = customDao.list(params);
//        return new customWarpper(list).warp();
        return list;
    }
    /**
     * 跳转到修改
     */
    @RequestMapping("/Custom_update/{id}")
    public String toEdit(@PathVariable Integer id, Model model) {
        Custom Custom =customMapper.selectById(id);
        Map<String, Object> menuMap = BeanKit.beanToMap(Custom);
        model.addAttribute("businessTypeList", ConstantFactory.me().getBusinessList());
        model.addAttribute("industryTypeList", ConstantFactory.me().getIndustryList());
        model.addAttribute("propertyList", ConstantFactory.me().getPropertyList());
        model.addAttribute("Custom",menuMap);
        return PREFIX + "Custom_edit.html";
    }
    /**
     * 跳转到新增
     */
    @RequestMapping("/Custom_add")
    public String toAdd(Model model) {
        model.addAttribute("businessTypeList", ConstantFactory.me().getBusinessList());
        model.addAttribute("industryTypeList", ConstantFactory.me().getIndustryList());
        model.addAttribute("propertyList", ConstantFactory.me().getPropertyList());
        return PREFIX + "Custom_add.html";
    }
    /**
     * 修改
     * @return
     */
    @RequestMapping("/edit")
    @BussinessLog(value = "修改观众",  dict = Dict.CUSTOM_DICT)
    @Permission
    @ResponseBody
    public Tip update(CustomDto params) {
        if(ToolUtil.isEmpty(params)){
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        LogObjectHolder.me().set(customMapper.selectById(params.getId()));
        customService.updateCustom(params);
        return SUCCESS_TIP;
    }

    /**
     * 新增
     * @return
     */
    @RequestMapping("/add")
    @BussinessLog(value = "新增观众", dict = Dict.CUSTOM_DICT)
    @Permission
    @ResponseBody
    public Tip add(CustomDto params) {
        customService.addCustom(params);
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    @BussinessLog(value = "删除观众",  dict = Dict.CUSTOM_DICT)
    @Permission
    @ResponseBody
    public Tip delete(@PathVariable Integer id) {
        if(ToolUtil.isEmpty(id)){
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        customService.deleteCustom(id);
        return SUCCESS_TIP;
    }
    /**
     * 批量删除
     */
    @RequestMapping("/batchDelete")
    @BussinessLog(value = "批量删除观众",  dict = Dict.CUSTOM_DICT)
    @Permission
    @ResponseBody
    public Tip delete(@RequestParam String ids) {
        if(ToolUtil.isEmpty(ids)){
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        List<String> list = Arrays.asList(ids.split(","));
        for(String id:list){
           customService.deleteCustom(Integer.valueOf(id));
        }
        return SUCCESS_TIP;
    }
    /**
     * 跳转用户详情
     */
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        Custom Custom = this.customMapper.selectById(id);
        model.addAttribute(Custom);

//        //商业性质1
//        String businessType1 = Custom.getBusinessType1();
//        String businessType1Name = "";
//        if (ToolUtil.isNotEmpty(businessType1)) {
//            businessType1Name = ConstantFactory.me().getCustomName(businessType1);
//        }
//        model.addAttribute("businessType1Name", businessType1Name);
//        //商业性质2
//        String businessType2 = Custom.getBusinessType2();
//        String businessType2Name = "";
//        if (ToolUtil.isNotEmpty(businessType2)) {
//            businessType2Name = ConstantFactory.me().getCustomName(businessType1);
//        }
//        model.addAttribute("businessType2Name", businessType2Name);
//        //商业性质3
//        String businessType3 = Custom.getBusinessType3();
//        String businessType3Name = "";
//        if (ToolUtil.isNotEmpty(businessType3)) {
//            businessType3Name = ConstantFactory.me().getCustomName(businessType1);
//        }
//        model.addAttribute("businessType3Name", businessType3Name);
//
//        //行业性质
//        String industryType = Custom.getIndustryType();
//        String industryTypeName = "";
//        if (ToolUtil.isNotEmpty(industryType)) {
//            industryTypeName = ConstantFactory.me().getCustomName(industryType);
//        }
//        model.addAttribute("industryTypeName", industryTypeName);
//
//        //商业性质3
//        String property = Custom.getProperty();
//        String propertyName = "";
//        if (ToolUtil.isNotEmpty(property)) {
//            propertyName = ConstantFactory.me().getCustomName(property);
//        }
//        model.addAttribute("propertyName", propertyName);


        //创建人
        String createUserName = "";
        Integer createUserId = Custom.getCreateUser();
        if (ToolUtil.isNotEmpty(createUserId)) {
            createUserName = ConstantFactory.me().getUserNameById(createUserId);
        }
        model.addAttribute("createUserName", createUserName);
        //修改人
        String updateUserName = "";
        Integer updateUserId = Custom.getUpdateUser();
        if (ToolUtil.isNotEmpty(updateUserId)) {
            updateUserName = ConstantFactory.me().getUserNameById(updateUserId);
        }
        model.addAttribute("updateUserName", updateUserName);
        return PREFIX + "Custom_detail.html";
    }

//    /**
//     * 导出列表
//     */
//    @RequestMapping("/export")
//    @Permission
//    public void export(@RequestParam String fields, CustomDto params) {
//        LinkedHashMap<String, String> linkedHashMap = new CustomExport().getDictory();
//        List<String> lableList = new ArrayList<>();
//        List<String> fieldList = new ArrayList<>();
//        String[] fieldArr = fields.split(",");
//        if (ToolUtil.isNotEmpty(linkedHashMap) && fieldArr != null && fieldArr.length > 0) {
//            Iterator iter = linkedHashMap.entrySet().iterator();
//            while (iter.hasNext()) {
//                Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
//                String key = entry.getKey();
//                String val = entry.getValue();
//                if (ToolUtil.isContainWithArray(fieldArr, val)) {//如果包含选择的字段
//                    fieldList.add(val);
//                    lableList.add(key);
//                }
//
//            }
//        }
//        List<Map<String, Object>> list = CustomDao.list(params);
//        list =(List)new CustomWarpper(list).warp();
//        StringBuffer sb = new StringBuffer();
//        //如果当前导出字段只勾选了email邮箱或者phone手机号，那么将邮箱或者手机号拼起来导出，用“,”隔开
//        if(fieldList.size()==1&&fieldList.get(0).equals("email")){
//                for(Map<String, Object> map:list){
//                    sb.append(map.get("email"));
//                    sb.append(",");
//                }
//                Map<String,Object> emailMap = new HashMap<>();
//                if (',' == sb.charAt(sb.length() - 1)) {
//                    sb = sb.deleteCharAt(sb.length() - 1);
//                }
//                emailMap.put("email",sb);
//                list.clear();
//                list.add(emailMap);
//        }
//        if(fieldList.size()==1&&fieldList.get(0).equals("phone")){
//            for(Map<String, Object> map:list){
//                sb.append(map.get("phone"));
//                sb.append(",");
//            }
//            Map<String,Object> emailMap = new HashMap<>();
//            if (',' == sb.charAt(sb.length() - 1)) {
//                sb = sb.deleteCharAt(sb.length() - 1);
//            }
//            emailMap.put("phone",sb);
//            list.clear();
//            list.add(emailMap);
//        }
//        ExcelReport report = new ExcelReport("观众信息", lableList.toArray(new String[lableList.size()]),
//                fieldList.toArray(new String[fieldList.size()]), null, list, super.getHttpServletResponse());
//        try {
//            report.export();
//        } catch (Exception e) {
//            // e.printStackTrace();
//            // TODO: handle exception
//        }
//    }
//    /**
//     * 跳转到导入
//     */
//    @RequestMapping("/import")
//    @Permission
//    public String importCustom(){
//        return PREFIX + "Custom_import.html";
//    }
//    /**
//     * 批量导入验证效验
//     */
//    @RequestMapping("/upload")
//    @ResponseBody
//    public Map<String, Object> upload(@Valid FileDto fileDto, HttpServletRequest request, BindingResult result) {
//        Map<String, Object> map = new HashMap<>();
//        if (result.hasErrors()) {
//            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
//        }
//        String fileName = fileDto.getFileName();
//        if (ToolUtil.isEmpty(fileName)) {
//            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
//        }
//        File tempFile = new File(victorProperties.getFileUploadTempPath() + fileName);
//        if (!tempFile.exists()) {
//            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
//        }
//        try {
//            return CustomService.importCustom(request, fileDto);
//        } catch (IOException e) {
//            // HSSFWorkbook异常
//            e.printStackTrace();
//            map.put("success", false);
//            return map;
//        }
//    }
//
//    /**
//     * 批量导入验证入库
//     */
//    @RequestMapping("/pushData2Base")
//    @ResponseBody
//    public Map<String, Object> pushData2Base(@Valid FileDto fileDto, HttpServletRequest request, BindingResult result) {
//        Map<String, Object> map = new HashMap<String, Object>();
//        if (result.hasErrors()) {
//            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
//        }
//        Object obj = request.getSession().getAttribute("Custom_IMPORT");
//        if (ToolUtil.isEmpty(obj)) {
//            throw new BussinessException(BizExceptionEnum.SERVER_ERROR);
//        }
//        try {
//            CustomService.putCustom2Database(request);
//            map.put("success", true);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BussinessException(BizExceptionEnum.SERVER_ERROR);
//        }
//        return map;
//    }
}
